#pragma once

#include "sprite.h"
#include "parentpanel.h"
#include "templatevectorlist.h"
#include "sanimationentry.h"

class SAnimationViewer : public ParentPanel
{
protected:
	TemplateVectorList<SAnimationEntry> m_animationEntries;
	Sprite * m_sprite;
	static void setAnimation(void * a_entry);
public:
	SAnimationViewer():m_sprite(0),m_animationEntries(10)
	{setChildrenScrollable(true);setAutoArrangeGrid(true);setDragAndDropChild(true);}
	/** use when frame contents change, recalculates rectangles */
	void refresh()
	{
		requestChildAreaRefresh();
		ParentPanel::refreshArea();
		// make sure the area stays visible
		ParentPanel::keyScroll(SPoint(0,0));
		setDirty(0);
	}
	void draw(SDL_Surface * a_surface)
	{
		if(m_sprite->getAnimationCount() == 0)
		{
			VSDL_drawString("No Animation! You must create an Animation! [+A]", 
				a_surface, this->getArea()->getPosition());
		}
		else
		{
			ParentPanel::draw(a_surface);
		}
	}
	void set(Sprite * a_sprite)
	{
		m_animationEntries.clear();
		// ask the parent panel to reset the UI
		removeAllChildren();
		m_sprite = a_sprite;
		SAnimationEntry * sae;
		int numberOfEntries = a_sprite->getAnimationCount();
		for(int a = 0; a < numberOfEntries; ++a)
		{
			m_animationEntries.add(SAnimationEntry(a_sprite, a));
			sae = &m_animationEntries.get(a);
				addChild(sae);
			sae->refreshArea();
			sae->setAction((ButtonCallbackFunction)setAnimation, sae);
		}
	}
	/** use when frames are added, reallocated rectangles */
	void hardRefresh()
	{
		set(m_sprite);
	}

	SFrame * addFrame()
	{
		SFrame * f = 0;
		if(m_sprite->getAnimationCount() == 0)
		{
			f = addAnimation();
		}
		else
		{
			f = m_sprite->getAnimation()->getFrames()->add();
			m_sprite->setFrameIndex(m_sprite->getFrameCount()-1);
			hardRefresh();
			printf("a: %d/%d,   f: %d/%d\n", 
				m_sprite->getAnimationIndex(), m_sprite->getAnimationCount(), 
				m_sprite->getFrameIndex(), m_sprite->getFrameCount());
			refresh();
		}
		return f;
	}
	SFrame * addAnimation()
	{
		m_sprite->getAnimations()->add();
		m_sprite->setAnimationIndex(m_sprite->getAnimationCount()-1);
		return addFrame();
	}
	bool handleEvent(const SDL_Event & e)
	{
		bool handled = false;
		bool dirty = true;
		switch(e.type)
		{
		case SDL_KEYDOWN:
			switch(e.key.keysym.sym)
			{
			case SDLK_a:
				addAnimation();
				dirty = true;
				break;
			case SDLK_f:
				addFrame();
				dirty = true;
				break;
			}
		}
		if(!handled)
		{
			handled = ParentPanel::handleEvent(e);
		}
		if(dirty)
			setDirty(0);
		return handled;
	}
};